import {isFunction, isObject} from "../utils/util";
import pageInitFn from "./pageInitFn";
import userFn from "./userFn";
import utilFn from "./utilFn";
import wxmlFn from "./wxmlFn";
import { debounce, once, throttle } from "./sectionFn";
import initComponent from "./initComponent";

const mergeFunctions = [
    pageInitFn,
    userFn,
    utilFn,
    wxmlFn,
    initComponent
]
const originProperties = [
    'data',
    'properties',
    'options'
];
const componentMethod = [
    'created',
    'attached',
    'ready',
    'moved',
    'detached',
    'definitionFilter'
];
const modifiers = { throttle, debounce, once };
export function setMerge(options,use) {
    const functions=[...mergeFunctions,...use]
    functions.forEach(x => {
        Object.keys(x).forEach(y => {
            if (componentMethod.includes(y)) {
                const originFunc = options[y]
                options[y] = function (...args) {
                    x[y].call(this, ...args)
                    return originFunc && originFunc.call(this, ...args)
                }
            } else if (isFunction(x[y])) {
                if(!options.methods)options.methods={}
                options.methods[y] = x[y]
            }
        })
    })
    applyFunctionModifiers(options);
    return options
}
function applyFunctionModifiers(options) {
    Object.entries(modifiers).forEach(([modifierName, modifierFn]) => {
        if (options[modifierName] && isObject(options[modifierName])) {
            const config = options.methods[modifierName];
            const time = config.time || 1000;
            Object.entries(config).forEach(([key, func]) => {
                if (typeof func === 'function') {
                    options.method[key] = modifierFn(func, time);
                }
            });
            delete options.methods[modifierName]; // 清理原始配置
        }
    });
}


